'use strict';
//定时器 // 自动生成考勤
const moment = require('moment');
const invokeAddTaskRecord = require('add-test-record'); //引入公共模块
const db = uniCloud.database();

function isWord(time , arrayList) {
	let flag = false
	for (var i = 0; i < arrayList.length; i++) {
		let item = arrayList[i]
		if(item.time == time){
			if(item.type == '休'){
				flag =  '0'
			}
			
			if(item.type == '班'){
				flag =  '8'
			}
			
			continue;
		}
	}
	
	return flag
}

exports.main = async (event, context) => {
	let startTime = new Date().getTime()
	let count = 0
	// 获取当前时间
	let date = new Date()

	let year = date.getFullYear().toString()
	let month = (date.getMonth() + 1).toString() >= 10 ? (date.getMonth() + 1).toString() : "0" + ((
		date.getMonth() + 1).toString())
	// 当前天
	let sky = date.getDate().toString() >= 10 ? (date.getDate()).toString() : "0" + ((
		date.getDate()).toString())

	let days = ['日', '一', '二', '三', '四', '五', '六']
	let day = days[date.getDay()]

	// 获取用户
	let userInfo = await db.collection('userList').get()
	
	// 获取休息日
	let result_date = await db.collection('festival_date').get() //获取数据
	console.log(result_date , 'result_date');
	try {
		for (let i = 0; i < userInfo.data.length; i++) {
			let item = userInfo.data[i]
			count++
			let parmse = {
				"date": sky,
				"createTime": `${year}-${month}-${sky}`,
				"workingHours": "8", //默认八小时
				"overtime": "0", //默认0 
				"leave": "0", //默认0
				"day": day,
				"userName": item.userName //默认何俊东
			}

			let word = isWord(`${year}-${month}-${sky}` , result_date.data)
			if (word) {
				parmse.workingHours = word
			} else {
				if (day == '日' || day == '六') {
					parmse.workingHours = '0'
				}
			}

			// 查询当前用户是否存在当日考勤
			let result = await uniCloud.callFunction({
				name: "overallSituation",
				data: {
					databaseName: "checkOnWorkAttendance", //考勤
					state: "look", //查询
					createTime: parmse.createTime,
					userName: parmse.userName
				}
			})

			let res = null
			if (result.result.data.length == 0) {
				res = await uniCloud.callFunction({
					name: "overallSituation",
					data: {
						databaseName: "checkOnWorkAttendance", //考勤
						state: "add", //查询
						...parmse
					}
				})
			}
			console.log(res, "res");
		}
		await invokeAddTaskRecord({
			name: "新增人员考勤记录", // 任务名称
			cloudFunctionName:"ceshi",
			status: "success", 
			executionTime: moment().format("YYYY-MM-DD HH:mm:ss"),  //执行时间
			duration: ((Date.now() - startTime) / 1000 )+ 's', //执行时长
			log: `为${count}名人员添加周${day}的考勤，日期${year}-${month}-${sky}`
		}, context); 
		
		return {
			code: 200,
			message: "操作成功"

		}
	} catch (e) {
		await invokeAddTaskRecord({
			name: "新增人员考勤记录", // 任务名称
			cloudFunctionName:"ceshi",
			status: "error", 
			executionTime: moment().format("YYYY-MM-DD HH:mm:ss"),  //执行时间
			duration: ((Date.now() - startTime) / 1000 )+ 's', //执行时长
			log: `添加人员考勤失败，`
		}, context); 
		//TODO handle the exception
		return {
			code: 500,
			message: "操作失败"
		}
	}


}